/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import database.MTDatabase;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 *
 * @author daolam
 */

@Singleton
@Startup
@ServerEndpoint(value = "/websocket")
public class MTServer {
    
    Logger logger = Logger.getLogger("MTServer");
    
    //<editor-fold desc="Property">
    private static Set<Session> _peers;
    private MTDatabase _db;
    //</editor-fold>
    
    //<editor-fold desc="Get/Set method">
    public MTDatabase getDBHandler()
    {
        return _db;
    }
    //</editor-fold>
    
    // <editor-fold desc="Server behavior">
    @PostConstruct
    private void onInitialized()
    {
        logger.info("onInitialized");
        _peers = Collections.synchronizedSet(new HashSet<Session>());
        _db = MTDatabase.getInstance();
    }
    
    @PreDestroy
    private void onDestroyed()
    {
        logger.info("onDestroyed");
    }
    // </editor-fold>
    
    // <editor-fold desc="Websocket Listener">
    @OnOpen
    private void onOpen(Session peer)
    {
        _peers.add(peer);
    }

    @OnClose
    private void onClose(Session peer)
    {
        _peers.remove(peer);
    }
    
    @OnMessage
    private void onMessage(String message, Session client) throws IOException, EncodeException
    {
        for(Session peer:_peers)
        {
            peer.getBasicRemote().sendObject(message);
        }
    }
    //</editor-fold>
}
